<template>
  <div>
    <el-form
      :inline="true"
      :model="formInline"
      class="demo-form-inline"
      style="margin: 20px 30px 0px"
    >
      <el-form-item>
        <el-input v-model="formInline.name" placeholder="名称"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          @click="handleQuery({ page: 1, size: pagination.pageSize })"
          >查询</el-button
        >
        <el-button type="primary" @click="addEbook()">新增</el-button>
      </el-form-item>
    </el-form>
    <el-table :data="ebooks" style="width: 100%">
      <el-table-column label="封面" width="100">
        <template #default="scope">
          <el-avatar
            shape="square"
            :size="50"
            :src="scope.row.cover"
            style="float: left; margin: 15px"
          ></el-avatar>
        </template>
      </el-table-column>

      <el-table-column label="名称" width="200">
        <template #default="scope">
          {{ scope.row.name }}
        </template>
      </el-table-column>

      <el-table-column label="分类" width="180">
        <template #default="scope">
          {{ getCategoryName(scope.row.category1Id) }}
          /
          {{ getCategoryName(scope.row.category2Id) }}
        </template>
      </el-table-column>

      <el-table-column label="文档数" width="100">
        <template #default="scope">
          {{ scope.row.docCount == null ? 10 : scope.row.docCount }}
        </template>
      </el-table-column>

      <el-table-column label="阅读数" width="100">
        <template #default="scope">
          {{ scope.row.viewCount == null ? 24555 : scope.row.viewCount }}
        </template>
      </el-table-column>

      <el-table-column label="点赞数" width="100">
        <template #default="scope">
          {{ scope.row.voteCount == null ? 100 : scope.row.voteCount }}
        </template>
      </el-table-column>

      <el-table-column label="操作" width="300">
        <template #default="scope">
          <router-link :to="'/admin/doc?ebookId='+scope.row.id"><el-button size="mini" type="primary">文档管理</el-button></router-link>&nbsp;&nbsp;
          <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>&nbsp;&nbsp;
          <el-dialog
            title="电子书表单"
            :width="500"
            v-model="dialogFormVisible"
            :modal="false"
          >
            <el-form :model="book" v-loading="loading">
              <el-form-item label="封面" :label-width="formLabelWidth">
                <el-input v-model="book.cover" autocomplete="off"></el-input>
              </el-form-item>

              <el-form-item label="名称" :label-width="formLabelWidth">
                <el-input v-model="book.name" autocomplete="off"></el-input>
              </el-form-item>

              <el-form-item label="分类" :label-width="formLabelWidth">
                <el-cascader
                  v-model="categoryIds"
                  :options="level1"
                  :props="{ label: 'name', value: 'id', children: 'children' }"
                  @change="handleChange"
                ></el-cascader>
              </el-form-item>

              <el-form-item label="描述" :label-width="formLabelWidth">
                <el-input
                  v-model="book.description"
                  autocomplete="off"
                ></el-input>
              </el-form-item>
            </el-form>
            <template #footer>
              <span class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="handleSave">确 认</el-button>
              </span>
            </template>
          </el-dialog>

          <el-popconfirm
            confirmButtonText="确认"
            cancelButtonText="取消"
            icon="el-icon-info"
            iconColor="red"
            title="删除后不可恢复，确认删除?"
            @confirm="handleDelete(scope.$index, scope.row)"
          >
            <template #reference>
              <el-button size="mini" type="danger">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      background
      layout="prev, pager, next"
      :total="pagination.total"
      :current-page.sync="pagination.current"
      :page-size="pagination.pageSize"
      @current-change="handleTableChange"
    >
    </el-pagination>
  </div>
</template>

<script>
import axios from "axios";
import { ref, reactive } from "vue";
import { defineComponent } from "vue";
import { ElMessage } from "element-plus";
import Tool from "../../util/tool";
export default {
  name: "AdminEbook",
  data() {
    return {
      dialogFormVisible: false,
      book: "",
      categoryIds: [],
      formLabelWidth: "120px",
      formComponentSize: "100px",
      loading: false,
    };
  },
  setup() {
    console.log("组件初始化成功");
    const ebooks = ref();
    const pagination = ref({
      current: 1,
      pageSize: 4,
      total: 0,
    });
    const formInline = ref();
    formInline.value = {};

    const level1 = ref();
    let categorys;
    /**
     * 分类数据查询
     **/
    const handleQueryCategory = () => {
      let _this = this;
      axios
        .get("/category/all")
        .then(function (response) {
          const data = response.data;
          if (data.success) {
            categorys = data.content;
            console.log("原始数组：", categorys);

            level1.value = [];
            level1.value = Tool.array2Tree(categorys, 0);
            console.log("树型结构：", level1.value);
            //加载完分类后，再加载电子书，否则如果分类树加载很慢，则电子书渲染会出错
            handleQuery({
              page: pagination.value.current,
              size: pagination.value.pageSize,
            });
          } else {
            ElMessage.error(data.message);
          }
        })
        .catch(function (error) {
          console.log(error);
        });
    };

    /**
     *获取分类名称
     */
    const getCategoryName = (cid) => {
      let result = "";
      categorys.forEach((item) => {
        if (item.id === cid) {
          result = item.name;
        }
      });
      return result;
    };

    /**
     * 数据查询
     **/
    const handleQuery = (params) => {
      let _this = this;
      axios
        .get("/ebook/list", {
          params: {
            page: params.page,
            size: params.size,
            name: formInline.value.name,
          },
        })
        .then(function (response) {
          const data = response.data;
          if (data.success) {
            ebooks.value = data.content.list;
            console.log("resp=>data.total:" + data.content.total);
            // 重置分页按钮
            console.log("params=>page=>" + params.page);
            pagination.value.total = data.content.total;
          } else {
            ElMessage.error(data.message);
          }
        })
        .catch(function (error) {
          console.log(error);
        });
    };

    /**
     * 表格点击页码时触发
     */
    const handleTableChange = (page) => {
      console.log("看看自带的分页参数都有啥：" + pagination);
      console.log("当前页码：" + pagination.value.current);
      console.log("一页显示的条数：" + pagination.value.pageSize);
      pagination.value.current = page;
      handleQuery({
        page: pagination.value.current,
        size: pagination.value.pageSize,
      });
    };

    onMounted: {
      console.log("onMounted=>2222");
      console.log("pagination.current=>" + pagination.value.current);
      console.log("pagination.pageSize=>" + pagination.value.pageSize);
      handleQueryCategory();
    }

    return {
      getCategoryName,
      level1,
      ebooks,
      pagination,
      handleTableChange,
      handleQuery,
      formInline,
    };
  },
  methods: {
    handleEdit(index, row) {
      console.log("index:" + index);
      console.log("row", row);
      this.dialogFormVisible = true;
      this.book = Tool.copy(row);
      this.categoryIds = [this.book.category1Id, this.book.category2Id];
    },
    handleDelete(index, row) {
      console.log("==========删除==========");
      console.log("index:" + index);
      console.log("row", row);
      const _this = this;
      _this.axios
        .delete("/ebook/delete/" + row.id)
        .then(function (response) {
          const data = response.data;
          if (data.success) {
            ElMessage.success({
              message: "操作成功！",
              type: "success",
            });

            //重新加载列表
            _this.handleQuery({
              page: _this.pagination.current,
              size: _this.pagination.pageSize,
            });
          }
        })
        .catch(function (error) {
          ElMessage.error("操作失败！");
          console.log(error);
        });
    },
    handleSave() {
      this.loading = true;
      console.log("pagination.current=>", this.pagination.current);
      const _this = this;
      _this.book.category1Id = _this.categoryIds[0];
      _this.book.category2Id = _this.categoryIds[1];
      _this.axios
        .post("/ebook/save", _this.book)
        .then(function (response) {
          _this.loading = false;
          const data = response.data;
          if (data.success) {
            ElMessage.success({
              message: "操作成功！",
              type: "success",
            });
            _this.dialogFormVisible = false;

            //重新加载列表
            _this.handleQuery({
              page: _this.pagination.current,
              size: _this.pagination.pageSize,
            });
          } else {
            ElMessage.error(data.message);
          }
        })
        .catch(function (error) {
          _this.loading = false;
          _this.dialogFormVisible = false;
          ElMessage.error("操作失败！");
          console.log(error);
        });
    },
    onSubmit() {
      console.log("submit!");
    },
    addEbook() {
      this.dialogFormVisible = true;
      this.book = {};
    },
  },
};
</script>

<style>
.el-pagination {
  margin-top: 15px;
  text-align: right;
  margin-bottom: 30px;
}
</style>
